#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <curl/curl.h>

#include"../comm/log.hpp"

using namespace std;
using namespace ns_log;

// Callback function to read email data
size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    string *data = static_cast<string *>(stream);
    size_t buffer_size = size * nmemb;

    if (data->empty())
        return 0; // End of data

    size_t to_copy = (buffer_size < data->size()) ? buffer_size : data->size();
    memcpy(ptr, data->c_str(), to_copy);
    data->erase(0, to_copy);
    return to_copy;
}

bool send_verification_email(const string &email, const string &verification_link)
{
    CURL *curl;
    CURLcode res;
    struct curl_slist *recipients = NULL;
    bool success = false;

    // Email content
    string email_data = "Subject: Verification Email\r\n\r\nPlease verify your email by clicking the following link: " + verification_link + "\r\n.\r\n";

    // Initialize libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if (curl)
    {
        // Set the SMTP server URL
        curl_easy_setopt(curl, CURLOPT_URL, "smtps://smtp.163.com:465");

        // Set the sender email and password
        curl_easy_setopt(curl, CURLOPT_USERNAME, "18781874454@163.com");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "DCTIGJTKKIAWHQVE");

        // Set the recipient email
        recipients = curl_slist_append(recipients, email.c_str());
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

        // Set the email sender
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "18781874454@163.com");

        // Email data
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
        curl_easy_setopt(curl, CURLOPT_READDATA, &email_data);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

        // Enable verbose logging
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        // Disable SSL certificate verification (for testing purposes)
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

        // Perform the request
        res = curl_easy_perform(curl);

        // Check for errors
        if (res == CURLE_OK)
        {
            success = true;
            LOG(INFO)<< "Email sent successfully!" << endl;
        }
        else
        {
            LOG(ERROR)<< "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        }

        // Clean up
        curl_slist_free_all(recipients);
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
    return success;
}
